/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim </a>, 2004
 */
package hk.com.carfield.action.process;

import hk.com.carfield.content.Content;
import hk.com.carfield.content.Editable;
import hk.com.carfield.core.Config;
import hk.com.carfield.core.ContentManager;
import hk.com.carfield.core.Context;
import hk.com.carfield.util.LogUtil;
import hk.com.carfield.util.StringUtil;
import hk.com.carfield.util.TemplateUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public final class Edit implements Process {
	// TODO add validation
	public File process(final Context c, final Request req, final File l) throws IOException {
		if (l.isDirectory()) {
			processDir(c.config, req, l);
			final File[] childs = l.listFiles(c.config.displayFilter());
			for (int i = 0; i < childs.length; i++) {
				if (!childs[i].isFile()) {
					LogUtil.error("!isFile: " + childs[i].getAbsolutePath(), c.mailMan);
					continue;
				}
				final String name = TemplateUtil.escape(childs[i].getName());
				final String value = req.getParameter(name);
				c.persistMan.persist(childs[i], value);
				Rename.rename(childs[i], req.getParameter(name + "_name"));
			}
		} else {
			final Content item = ContentManager.getContent(c, l);
			if (item instanceof Editable) {
				((Editable) item).process(req);
				c.cacheMan.remove(l);
			}
		}
		return l;
	}

	private void processDir(final Config config, final Request req, final File location) throws IOException {
		final File headerFile = new File(location, config.headerFileName), readmeFile = new File(location,
				config.readmeFileName);
		final String headerStr = req.getParameter(config.headerFileName);
		final String readmeStr = req.getParameter(config.readmeFileName);
		if (StringUtil.notBlank(headerStr)) {
			FileUtils.writeStringToFile(headerFile, headerStr, "UTF-8");
		} else {
			headerFile.delete();
		}
		if (StringUtil.notBlank(readmeStr)) {
			FileUtils.writeStringToFile(readmeFile, readmeStr, "UTF-8");
		} else {
			readmeFile.delete();
		}
	}

	public String actionCode() {
		return "editprocess";
	}

	public boolean adminOnly() {
		return true;
	}
}
